using UnityEngine;
using System.Collections;

[System.Serializable]

public class MapManager {
	
	public Vector3 map_position;
	
	public GameObject tile_prefab;
	public GameObject[, ] tiles;
	
	public int columns;
	public int lines;
	
	public float distance_between_columns;
	public float distance_between_lines;
	
	public float altura;
	
	public int NUM_bombs;
	
	public int[,] map;
	
	public static int Pattern_Bomb = 10;
	public static int Pattern_Normal = 9;

	public void InstantiateMap()
	{
		
		map = new int[this.lines, this.columns];
		
		int[] bombs = new int[NUM_bombs];
		
		for(int bomb = 0; bomb < bombs.Length; bomb++)
		{
			AddBomb(bomb, bombs);
		}
		
		for(int bomb = 0; bomb < bombs.Length; bomb++)
		{
			this.map[ bombs[bomb]/this.columns, bombs[bomb] % this.columns ] = MapManager.Pattern_Bomb;
		}

		for(int i = 0; i < this.lines; i++)
		{
			for(int j = 0; j < this.columns; j++)
			{
				
				GameObject tile = MonoBehaviour.Instantiate(this.tile_prefab, new Vector3(
				
				j*(tile_prefab.transform.localScale.x + this.distance_between_columns),
				
				this.altura,
				
				i*(tile_prefab.transform.localScale.z + this.distance_between_lines)),
				this.tile_prefab.transform.rotation) as GameObject;

				Tile tmpTile = tile.GetComponent<Tile>();
			
				tmpTile.SetData(i, j, i * this.columns + j, this);
				
				//this.tiles[i, j] = tile;
			}
		}	
	}
	
	public void AddBomb(int index, int[] bombs)
	{
		int tmpBomb = Random.Range(0, this.columns * this.lines);
			
		if(!hasBomb(tmpBomb, bombs))
		{
			bombs[index] = tmpBomb;
			int line = tmpBomb/this.columns;
			int column = tmpBomb%this.columns; 
			this.map[line, column] = MapManager.Pattern_Bomb;
			AtributteAround(line, column);
			
		}else
		{
			AddBomb(index, bombs);
		}
	}
	
	private void AtributteAround(int line, int column)
	{
		//left
		if(column -1 >= 0)
		{
			this.map[line, column -1]++;
		}
		
		//right
		if(column + 1 < this.columns)
		{
			this.map[line, column+1 ]++;
		}
		
		//up
		if(line + 1 < this.lines)
		{
			this.map[line +1, column]++;
		}
		
		//down
		if(line - 1 >= 0)
		{
			this.map[line -1, column]++;
		}
		
		//up/left
		if(line + 1 < this.lines && column -1 >= 0)
		{
			this.map[line +1, column -1]++;
		}
		
		//up/right
		if(line + 1 < this.lines && column + 1 < this.columns)
		{
			this.map[line +1, column +1]++;
		}
		
		//down/left
		if(line - 1 >= 0 && column -1 >= 0)
		{
			this.map[line -1, column -1]++;
		}
		
		//down/right
		if(line -1 >= 0 && column + 1 < this.columns)
		{
			this.map[line -1, column +1]++;
		}
	}
	
	private bool hasBomb(int bomb, int[] bombs)
	{
		foreach(int b in bombs)
		{
			if(b == bomb)
				return true;
		}
		
		return false;
	}
}
